package com.market.cash.ui.activity

import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.view.View
import com.market.cash.R
import com.market.cash.databinding.CashSettingBinding
import com.market.cash.http.ApiService
import com.market.cash.http.ApiService.addCommonParams
import com.market.cash.http.IHttpCallback
import com.market.cash.pro.ProActivity
import com.market.cash.utils.dialog.CashRootUserDataClearDialog
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import com.market.cash.utils.helper.SharedHelper
import org.json.JSONArray
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/28 16:16
 * @Annotation：设置
 */
class SettingActivity: ProActivity() {
    lateinit var binding: CashSettingBinding
    override fun getCashRootRootView(): View {
        binding = CashSettingBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initCashRootView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#F8F8F8"))
        setCashRootTitleBarColor(Color.parseColor("#FFFFFF"))
        setCashRootTitleBarVisibility(View.VISIBLE)
        setCashRootTextTitle(getString(R.string.me_setting))
        setCashRootRightBtnRes(R.mipmap.cash_kefu_black)
    }

    override fun initCashRootListener() {
        //客服
        rootViewBinding.imgKefu.setOnClickListener {
            KefuActivity.start(this,"Setting Page")
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_CUSTOMER,"Setting Page")
        }

        //清空用户数据
        binding.btnClearData.setOnClickListener {
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_USER_DATA_CLEAR)
            //存在未结清的账单
            if (isCashRootCheckUncleared()){
                showErrorTipsDialog(getString(R.string.user_data_clear_error),"Setting Page")
                return@setOnClickListener
            }
            showCashRootClearDataDialog()
        }

        //退出登录
        binding.btnLoginOut.setOnClickListener {
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_USER_LOGINOUT,"")
            //退出登录，需要移除用户保存的信息
            SharedHelper.onCashRootLoginOut()
            Handler(Looper.getMainLooper()).postDelayed({
                onIntent(LoginActivity::class.java)
            },300)
        }
    }

    override fun initCashRootData() {
        //获取版本名称
        val packageInfo = packageManager.getPackageInfo(this.packageName, 0)
        val versionCode = packageInfo.versionCode // 版本号（整数）
        binding.textVersion.text = String.format(getString(R.string.setting_version_name),packageInfo.versionName)

        //是否显示清空用户数据
        val isShowClearData = CashRootCustomConfigsHelper.isCashRootClearUserData()
        if (isShowClearData){
            binding.btnClearData.visibility = View.VISIBLE
        } else {
            binding.btnClearData.visibility = View.GONE
        }

        //牌照信息
        if (!CashRootCustomConfigsHelper.isCashRootShowLicense()){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(initCashRootLicenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 是否存在未结清的账单
     */
    private fun isCashRootCheckUncleared(): Boolean{
        val pData = SharedHelper.getCashRootSPString(SharedHelper.CashRoot_SPKEY.CASHROOT_PRODUCT)
        if (pData.isNotEmpty()){
            val objArray = JSONArray(pData)
            for (i in 0..<objArray.length()){
                val item = objArray.optJSONObject(i)
                val status = item.optString("status")
                //存在 审核中、放款中 || 待还款
                if (status == "PENDING" || status == "REPAYMENT"){
                    return true
                }
            }
        }
        return false
    }

    /**
     * 清空用户数据dialog
     */
    private fun showCashRootClearDataDialog(){
        val clearDialog = CashRootUserDataClearDialog(this,object : CashRootUserDataClearDialog.IDialogCallback{
            override fun onCashRootConfirmClick() {
                loadCashRootClearUserDataAction()
            }
        })
        clearDialog.setCancelable(true)
        clearDialog.setCanceledOnTouchOutside(true)
        clearDialog.show()
    }

    /**
     * 清除用户数据
     */
    private fun loadCashRootClearUserDataAction(){
        showCashRootLoading()
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_COMMON_URL)
        val params = JSONObject().addCommonParams().apply {
            put("path",ApiService.API_PATH.CASHROOT_API_USER_DATA_CLEAR_PATH)
        }
        doPostAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hideCashRootLoading()
                //退出登录，需要移除用户保存的信息
                SharedHelper.onCashRootLoginOut()
                onIntent(LoginActivity::class.java)
            }
            override fun onRequestError(error: JSONObject) {
                showCashRootToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                hideCashRootLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_USER_SETTING_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_USER_SETTING_END)
    }
}